package com.bsg.upm.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.bsg.upm.check.BusinessSubSystemCheck;
import com.bsg.upm.check.CheckResult;
import com.bsg.upm.constant.OperateDictConstants;
import com.bsg.upm.constant.OperateDictTypeConstants;
import com.bsg.upm.dto.BusinessSubSystemDto;
import com.bsg.upm.dto.BusinessSystemDto;
import com.bsg.upm.entity.BusinessSubSystemEntity;
import com.bsg.upm.entity.BusinessSystemEntity;
import com.bsg.upm.exception.APIException;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.http.RespJsonFactory;
import com.bsg.upm.util.DateUtils;
import com.bsg.upm.util.PrimaryKeyUtils;

/**
 * 业务子系统管理业务处理类
 * 
 * @author HCK
 *
 */
@Service
public class BusinessSubSystemService extends BaseService {

	@Resource
	private BusinessSystemService businessSystemService;

	@Resource
	private BusinessSubSystemCheck businessSubSystemCheck;

	/**
	 * 业务子系统查询
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson list(Map<String, Object> paramMap) throws APIException {
		try {
			// 结果集
			JSONArray results = new JSONArray();

			// 获取指定条件的业务子系统
			List<BusinessSubSystemEntity> businessSubSystems = businessSubSystemDao.list(paramMap);

			for (BusinessSubSystemEntity businessSubSystem : businessSubSystems) {
				// 构建业务子系统展示对象
				BusinessSubSystemDto dto = buildShowDto(businessSubSystem, false);
				results.add(dto);
			}

			return RespJsonFactory.buildOK(results);
		} catch (Exception e) {
			logger.error("业务子系统查询异常", e);
			throw new APIException("业务子系统查询异常:" + e.getMessage());
		}
	}

	/**
	 * 业务子系统详情
	 * 
	 * @param businessSubSystemId
	 *            业务子系统编码
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson get(String businessSubSystemId) throws APIException {
		try {
			// 获取指定的业务子系统
			BusinessSubSystemEntity businessSubSystem = businessSubSystemDao.get(businessSubSystemId);
			if (businessSubSystem == null) {
				return RespJsonFactory.build(HttpStatus.SC_GONE, "该业务子系统不存在");
			}

			// 构建业务子系统展示对象
			BusinessSubSystemDto dto = buildShowDto(businessSubSystem, true);

			return RespJsonFactory.buildOK(dto);
		} catch (Exception e) {
			logger.error("业务子系统获取异常", e);
			throw new APIException("业务子系统获取异常:" + e.getMessage());
		}
	}

	/**
	 * 业务子系统新增
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson save(Map<String, Object> paramMap) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_ADD;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 业务子系统新增检查
			CheckResult chkRS = businessSubSystemCheck.checkSave(paramMap);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			// 构建业务子系统对象
			BusinessSubSystemEntity businessSubSystem = buildBusinessSubSystem(paramMap);
			businessSubSystemDao.save(businessSubSystem);

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_BUSINESS_SUBSYSTEM, operateAcion, businessSubSystem.getId(),
					businessSubSystem.getName(), businessSubSystem.getCreateDateTime());

			return RespJsonFactory.buildCreated();
		} catch (Exception e) {
			logger.error("业务子系统" + operateAcionText + "异常", e);
			throw new APIException("业务子系统" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 业务子系统编辑
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson update(Map<String, Object> paramMap) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_UPDATE;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 业务子系统编辑检查
			CheckResult chkRS = businessSubSystemCheck.checkUpdate(paramMap);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			// 构建业务子系统对象
			BusinessSubSystemEntity businessSubSystem = buildBusinessSubSystemToUpdate(paramMap);
			businessSubSystemDao.update(businessSubSystem);

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_BUSINESS_SUBSYSTEM, operateAcion, businessSubSystem.getId(),
					businessSubSystem.getName());

			return RespJsonFactory.buildOK();
		} catch (Exception e) {
			logger.error("业务子系统" + operateAcionText + "异常", e);
			throw new APIException("业务子系统" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 业务子系统删除
	 * 
	 * @param id
	 *            业务子系统编码
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson remove(String id) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_REMOVE;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 获取指定的业务子系统
			BusinessSubSystemEntity businessSubSystem = businessSubSystemDao.get(id);

			// 业务子系统删除检查
			CheckResult chkRS = businessSubSystemCheck.checkRemove(businessSubSystem);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			businessSubSystemDao.remove(id);

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_BUSINESS_SUBSYSTEM, operateAcion, businessSubSystem.getId(),
					businessSubSystem.getName());

			return RespJsonFactory.buildNoContent();
		} catch (Exception e) {
			logger.error("业务子系统" + operateAcionText + "异常", e);
			throw new APIException("业务子系统" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 构建业务子系统基础展示对象
	 * 
	 * @param businessSubSystem
	 *            业务子系统对象
	 * @return 业务子系统基础展示对象
	 */
	public BusinessSubSystemDto buildBusinessSubSystemBaseDto(BusinessSubSystemEntity businessSubSystem) {
		BusinessSubSystemDto dto = new BusinessSubSystemDto();
		dto.setId(businessSubSystem.getId());
		dto.setName(businessSubSystem.getName());
		dto.setDescription(businessSubSystem.getDescription());
		dto.setCreateDateTime(DateUtils.dateTimeToString(businessSubSystem.getCreateDateTime()));
		return dto;
	}

	/**
	 * 构建业务子系统展示对象
	 * 
	 * @param businessSubSystem
	 *            业务子系统对象
	 * @param showDetail
	 *            是否展示详情
	 * @return 业务子系统展示对象
	 */
	private BusinessSubSystemDto buildShowDto(BusinessSubSystemEntity businessSubSystem, boolean showDetail) {
		BusinessSubSystemDto dto = buildBusinessSubSystemBaseDto(businessSubSystem);
		BusinessSystemEntity businessSystem = businessSubSystem.getBusinessSystem();
		if (businessSystem != null) {
			BusinessSystemDto businessSystemDto = businessSystemService.buildBusinessSystemBaseDto(businessSystem);
			dto.setBusinessSystem(businessSystemDto);
		}
		return dto;
	}

	/**
	 * 构建业务子系统对象
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return 业务子系统对象
	 */
	private BusinessSubSystemEntity buildBusinessSubSystem(Map<String, Object> paramMap) {
		BusinessSubSystemEntity businessSubSystem = new BusinessSubSystemEntity();
		businessSubSystem.setId(PrimaryKeyUtils.uniqueId());
		businessSubSystem.setName(StringUtils.trim((String) paramMap.get("name")));
		businessSubSystem.setDescription(StringUtils.trim((String) paramMap.get("description")));
		BusinessSystemEntity businessSystem = new BusinessSystemEntity();
		businessSystem.setId(StringUtils.trim((String) paramMap.get("businessSystem")));
		businessSubSystem.setBusinessSystem(businessSystem);
		businessSubSystem.setCreateDateTime(systemDao.getCurrentDateTime());
		return businessSubSystem;
	}

	/**
	 * 构建业务子系统对象用于更新操作
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return 业务子系统对象
	 */
	private BusinessSubSystemEntity buildBusinessSubSystemToUpdate(Map<String, Object> paramMap) {
		BusinessSubSystemEntity businessSubSystem = businessSubSystemDao
				.get((String) paramMap.get("businessSubSystemId"));

		if (paramMap.containsKey("name")) {
			businessSubSystem.setName(StringUtils.trim((String) paramMap.get("name")));
		}

		if (paramMap.containsKey("description")) {
			businessSubSystem.setDescription(StringUtils.trim((String) paramMap.get("description")));
		}

		if (paramMap.containsKey("businessSystem")) {
			BusinessSystemEntity businessSystem = new BusinessSystemEntity();
			businessSystem.setId(StringUtils.trim((String) paramMap.get("businessSystem")));
			businessSubSystem.setBusinessSystem(businessSystem);
		}
		return businessSubSystem;
	}

}
